﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace WatchDog.Core
{
    public class ProcessHelper
    {
        public static bool IsStarting(string fullPath)
        {
            try
            {
                var process = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fullPath));
                return process.Any(c => c.MainModule.FileName == fullPath);
            }
            catch
            {
                return false;
            }
        }

        public static double GetStatus(string fullPath)
        {
            try
            {
                var process = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fullPath));
                var m = process.FirstOrDefault(c => c.MainModule.FileName == fullPath);
                if (m != default)
                {
                    return (DateTime.Now - m.StartTime).TotalMinutes;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        public static void Starting(string fullPath)
        {
            try
            {
                var proc = new Process();
                proc.StartInfo.FileName = Path.GetFileName(fullPath);
                proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(fullPath);
                proc.Start();
            }
            catch
            {

            }
        }

        public static void Stop(string fullPath)
        {
            try
            {
                var process = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(fullPath)).Where(c => c.MainModule.FileName == fullPath);

                if (process.Any())
                {
                    foreach (var item in process)
                    {
                        item.Kill();
                    }
                }
            }
            catch
            {
 
            }
        }
    }
}
